import React, { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import * as api from './server';
import dayjs from './day';
import './css/topic.css'
const Topic = () => {
  const { id } = useParams();
  const [topic, setTopic] = useState({});
  const [collect, setCollect] = useState([]);
  const [isCol, setIsCol] = useState(false);
  useEffect(() => {
    api.getTopic(id)
      .then(res => {
        console.log(1)
        setTopic(res.data);
      })
    api.getCollect('HL1115')
      .then(res => {
        console.log(2)
        setCollect(res.data)
        if (res.data.filter(item => item.id == id).length==1) {
          setIsCol(true);
        }else{
          setIsCol(false);
        }
      })
  }, [])

  const createCollect = () => {
    if (isCol == false) {
      // 收藏主题
      api.createCollect({
        accesstoken: 'e73b268b-f5d2-4ff1-8fd9-3581b84962e2',
        topic_id: id
      })
        .then(res => {
          console.log(res)
          setIsCol(true);
          console.log('收藏成功!')
        })
    } else {
      // 取消收藏
      api.delCollect({
        accesstoken: 'e73b268b-f5d2-4ff1-8fd9-3581b84962e2',
        topic_id: id
      })
        .then(res => {
          setIsCol(false);
          console.log('取消收藏!')
        })
    }

  }

  return (
    <div>
      <button onClick={createCollect} >{isCol === true ? '取消收藏' : '收藏帖子'}</button>
      <h2>{topic.title}</h2>
      <h3>发布于{dayjs(topic.create_at).fromNow()}</h3>
      <div dangerouslySetInnerHTML={{ __html: topic.content }}></div>
    </div>
  );
};

export default Topic;
